package com.xwn.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.exception.excel.ExcelExportException;
import cn.afterturn.easypoi.exception.excel.enums.ExcelExportEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 关于使用easypoi导入导出实现
 * @author duandw
 */
public class EasyPoiUtils {

    private static final Logger logger = LoggerFactory.getLogger(EasyPoiUtils.class);

    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\\\.(?i)(xls)$");
    }

    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\\\.(?i)(xlsx)$");
    }

    /**
     * 导入excel 文件路径形式
     *
     * @param filePath   文件全路径
     * @param titleRows  标题开始行
     * @param headerRows 数据开始行
     * @param pojoClass  Excel对象Class
     * @param <T>        t
     * @return list
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(titleRows);
        importParams.setHeadRows(headerRows);
        return ExcelImportUtil.importExcel(new File(filePath), pojoClass, importParams);
    }

    /**
     * 导入excel MultipartFile文件形式
     *
     * @param file       文件
     * @param titleRows  标题开始行
     * @param headerRows 数据开始行
     * @param pojoClass  Excel对象Class
     * @param <T>        t
     * @return list
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception {
        if (file == null) {
            return null;
        }
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(titleRows);
        importParams.setHeadRows(headerRows);
        return EasyPoiUtils.importExcel(file.getInputStream(), pojoClass, importParams);
    }

    /**
     * 导入excel MultipartFile文件形式
     * 支持校验,支持Key-Value
     *
     * @param file         文件
     * @param importParams ImportParams
     * @param pojoClass    Excel对象Class
     * @param <T>          t
     * @return result
     */
    public static <T> ExcelImportResult<T> importExcelMore(MultipartFile file, ImportParams importParams, Class<T> pojoClass) throws Exception {
        return ExcelImportUtil.importExcelMore(file.getInputStream(), pojoClass, importParams);
    }

    /**
     * 导入excel 数据IO流形式
     *
     * @param input        流
     * @param pojoClass    Excel对象Class
     * @param importParams ImportParams
     * @param <T>          t
     * @return list
     * @throws Exception e
     */
    public static <T> List<T> importExcel(InputStream input, Class<T> pojoClass, ImportParams importParams) throws Exception {
        return ExcelImportUtil.importExcel(input, pojoClass, importParams);
    }

    /**
     * 导出Excel 默认格式创建表头
     *
     * @param list      数据List
     * @param title     表头名称
     * @param sheetName sheet表名
     * @param pojoClass Excel对象Class
     * @param fileName  文件名
     * @param response  response
     * @throws Exception e
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws Exception {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    /**
     * 导出Excel map多sheet形式导出
     *
     * @param list     Excel对象数据List
     * @param fileName 文件名
     * @param response response
     * @throws Exception e
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }

    /**
     * 导出Excel 是否创建表头
     *
     * @param list           Excel对象数据List
     * @param title          表头名称
     * @param sheetName      sheet表名
     * @param pojoClass      Excel对象Class
     * @param fileName       文件名
     * @param isCreateHeader 是否创建表头
     * @param response       response
     * @throws Exception e
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,
                                   String fileName, boolean isCreateHeader, HttpServletResponse response) throws Exception {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * 导出Excel 常规导出方式
     *
     * @param list         Excel对象数据List
     * @param pojoClass    Excel对象Class
     * @param fileName     文件名
     * @param response     response
     * @param exportParams 导入参数设置
     * @throws Exception
     */
    public static void defaultExport(List<?> list, Class<?> pojoClass, String fileName,
                                     HttpServletResponse response, ExportParams exportParams) throws Exception {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) {
            downloadExcel(fileName, response, workbook);
        }
    }

    /**
     * 导出Excel map多sheet导出方式
     *
     * @param list     Excel对象数据List
     * @param fileName 文件名
     * @param response response
     * @throws Exception e
     */
    public static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) {
            downloadExcel(fileName, response, workbook);
        }
    }

    /**
     * 下载Excel
     *
     * @param fileName 文件名
     * @param response response
     * @param workbook workbook
     * @throws Exception e
     */
    public static void downloadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            //告诉浏览器数据的文件格式
            response.setHeader("content-Type", "application/vnd.ms-excel");
            //告诉浏览器文件的名字和类型
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            logger.error("excel文件下载失败!", e);
            throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, e.getCause());
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, e.getCause());
            }
        }
    }

    /**
     * 获得Workbook对象
     *
     * @param file 文件
     * @return workbook
     * @throws IOException e
     */
    public static Workbook getWorkBook(MultipartFile file) throws IOException {
        //目的是兼容03和07版excel
        InputStream inS = file.getInputStream();
        Workbook workbook;
        try {
            workbook = new HSSFWorkbook(inS);
        } catch (Exception e) {
            inS = file.getInputStream();
            workbook = new XSSFWorkbook(inS);
        }
        return workbook;
    }

}
